<template>
  <div class="VIP-view">
    <PageHeader title="超级会员"/>
    <div class="top-container">
      <div class="information">
        <VanImage
            round
            width="4rem"
            height="4rem"
            :src="require('@/assets/backgrounds/user.jpg')"
        />
        <div class="info">
          <span class="title">{{ username }}</span>
          <div class="membership">
            <p class="membership-text">{{ membershipLevel }}</p>
          </div>
        </div>
      </div>
      <div class="point">
        <p>当前积分:{{ score }}</p>
        <p>距下一等级:{{ nextLevelPoints }}</p>
      </div>
    </div>

    <div class="coupon" v-for="coupon in coupons" :key="coupon.id">
      <van-row gutter="20">
        <van-col span="8" class="count">
          <p style="font-size: 24px"><span style="font-size: 15px;font-weight: bold">¥</span> {{ coupon.count }}</p>
        </van-col>
        <van-col span="8" class="couponName">{{ coupon.name }}</van-col>
        <van-col span="8" class="condition">
          <van-button
              round
              style="height: 30px;border-color: #FA6408;color: #FA6408"
              :disabled="!canReceiveCoupon(coupon)"
              @click="submit(coupon)"
          >
            {{ canReceiveCoupon(coupon) ? '领取' : '不可领取' }}
          </van-button>
        </van-col>
      </van-row>
      <van-row gutter="20">
        <van-col span="8" class="condition">
          满{{ coupon.condition }}可用
        </van-col>
        <van-col span="8" style="font-size: 14px">所有商品可用</van-col>
        <van-col span="8">
          <van-count-down :time="time" />
        </van-col>
      </van-row>
    </div>
  </div>
</template>

<script>
import PageHeader from "@/components/PageHeader.vue";
import { Image as VanImage, Col as VanCol, Row as VanRow, Button as VanButton, CountDown as VanCountDown } from "vant";
import http from "@/plugins/http";

export default {
  name: "VIPView",
  components: { PageHeader, VanImage, VanCol, VanRow, VanButton, VanCountDown },
  data() {
    return {
      username: "",
      membershipLevel: "",
      score: 0,
      coupons: [
        { id: 1, count: 5, name: "黄金券", condition: 100 },
        { id: 2, count: 10, name: "白金券", condition: 200 },
        { id: 3, count: 20, name: "钻石券", condition: 300 }
      ],
      time: 0,
      userCoupons: []
    };
  },
  computed: {
    nextLevelPoints() {
      if (this.score < 500) {
        return 500 - this.score;
      } else if (this.score < 1000) {
        return 1000 - this.score;
      } else if (this.score < 1500) {
        return 1500 - this.score;
      } else {
        return 0;
      }
    }
  },
  activated() {
    this.calculateTimeRemaining();
    this.fetchUserInfo();
    this.fetchUserCoupons();
  },
  mounted() {
    this.calculateTimeRemaining();
    this.fetchUserInfo();
    this.fetchUserCoupons();
  },
  methods: {
    calculateTimeRemaining() {
      const now = new Date();
      const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
      this.time = endOfDay - now;
    },
    submit(coupon) {
      if (this.membershipLevel === "黄金会员" && (coupon.name === "白金券" || coupon.name === "钻石券")) {
        this.$toast.fail("权限不足，无法领取该优惠券");
        return;
      } else if (this.membershipLevel === "白金会员" && coupon.name === "钻石券") {
        this.$toast.fail("权限不足，无法领取该优惠券");
        return;
      }

      const existingCoupon = this.userCoupons.find(userCoupon => userCoupon.name === coupon.name);
      if (existingCoupon) {
        this.$toast.fail("您已领取过该优惠券");
        return;
      }

      const couponData = {
        username: this.username,
        count: coupon.count,
        name: coupon.name,
        condition: coupon.condition
      };

      http.post('/coupon/add', couponData)
          .then(response => {
            if (response.statusCode === '200') {
              this.$toast.success("优惠券领取成功！");
              this.fetchUserCoupons();
            } else {
              this.$toast.fail("领取失败，请重试");
            }
          })
          .catch(error => {
            console.error("领取优惠券时出错:", error);
            this.$toast.fail("领取失败，请稍后重试");
          });
    },
    fetchUserInfo() {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if (storedUser) {
        http.get(`/user/getUserInfo/${storedUser}`)
            .then(response => {
              const user = response.data;
              this.username = user.username;
              this.score = user.score;
              switch (user.userType) {
                case 1:
                  this.membershipLevel = "黄金会员";
                  break;
                case 2:
                  this.membershipLevel = "白金会员";
                  break;
                case 3:
                  this.membershipLevel = "钻石会员";
                  break;
                default:
                  this.membershipLevel = "普通会员";
              }
            })
            .catch(error => {
              console.error("获取用户信息出错:", error);
            });
      } else {
        console.error("没有用户登录");
      }
    },
    fetchUserCoupons() {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      http.get(`/coupon/user/${storedUser}`)
          .then(response => {
            this.userCoupons = response.data;
          })
          .catch(error => {
            console.error("获取用户优惠券信息出错:", error);
          });
    },
    canReceiveCoupon(coupon) {
      if (this.membershipLevel === "黄金会员" && (coupon.name === "白金券" || coupon.name === "钻石券")) {
        return false;
      } else if (this.membershipLevel === "白金会员" && coupon.name === "钻石券") {
        return false;
      }

      const existingCoupon = this.userCoupons.find(userCoupon => userCoupon.name === coupon.name);
      return !existingCoupon;
    }
  }
}
</script>

<style scoped>
.VIP-view {
  background-color: #F6F7F9;
  height: 100vh;
}

.information {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
}

.info {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
}

.title {
  background: linear-gradient(90deg, #433C54, #1F212D);
  -webkit-background-clip: text;
  color: transparent;
  font-weight: bold;
}

.membership {
  margin-top: 5px;
  height: 25px;
}

.membership-text {
  background: linear-gradient(90deg, #97758F, #343146);
  -webkit-background-clip: text;
  color: transparent;
  font-weight: bold;
}

.top-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  background: linear-gradient(to bottom, #faeaea, #f6f7f9);
  padding: 15px 10px;
}

.point {
  margin-bottom: 30px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  background: linear-gradient(90deg, #97758F, #343146);
  -webkit-background-clip: text;
  color: transparent;
  margin-right: 20px;
  padding: 5px;
  border-radius: 20px;
}

.coupon {
  padding-bottom: 20px;
  padding-top: 20px;
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  border-radius: 10px;
  background-color: white;
}

.count {
  padding-left: 20px;
  color: red;
}

.couponName {
  color: #FFBD66;
}

.condition {
  padding-left: 15px;
  color: red;
  font-size: 12px;
}

.van-button[disabled] {
  background-color: #ccc;
  border-color: #ccc;
  color: white;
}
</style>